package com.xebest.web.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.umf.b2b.model.bindcard.BindcardConfirm;
import com.umf.b2b.model.bindcard.BindcardEnterprise;
import com.umf.b2b.model.bindcard.BindcardOrder;
import com.umf.b2b.model.register.RegisterPersonal;
import com.umf.b2b.model.register.RegisterSubmer;
import com.umpay.util.CipherUtil;
import com.xebest.api.dto.PayUmApplyDTO;
import com.xebest.common.base.controller.BaseController;
import com.xebest.common.base.controller.BaseResponse;
import com.xebest.common.enums.whitelist.WhiteListCheckStateEnum;
import com.xebest.web.form.PayUmApplyForm;
import com.xebest.web.mapper.read.PayUmApplyReadMapper;
import com.xebest.web.mapper.write.PayUmApplyWriteMapper;
import com.xebest.web.model.PayUmApply;
import com.xebest.web.model.base.XePageInfo;
import com.xebest.web.service.PayUmApplyService;
import com.xebest.web.view.ErpUserInfo;
import org.apache.poi.hssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @desc:
 * @author: 任建波
 * @createTime: 2019/5/18 13:18
 * @history:
 * @version:v1.0
 */
@Service
public class PayUmApplyImpl implements PayUmApplyService {

    private Logger logger = LoggerFactory.getLogger(PayUmApplyImpl.class);

    @Autowired
    private PayUmApplyWriteMapper payUmApplyWriteMapper;
    @Autowired
    private PayUmApplyReadMapper payUmApplyReadMapper;
    @Autowired
    private Environment env;

    /*
    注册企业/个体商户联动链金
     */
    @Override
    @Transactional(value = "writeTransactionManager")
    public BaseResponse addPayUmApplyEnterprise(PayUmApplyForm payUmApplyForm, ErpUserInfo userInfo) {
        BaseController baseController = new BaseController();

        try {
            //企业商户入网
            RegisterSubmer registerMer = new RegisterSubmer();
            registerMer.setMer_id("90000002");  //平台商户与联动签约后，链金平台分配给商户分配的唯一身份编号
            registerMer.setOrder_id(String.valueOf(new Date().getTime()));  //订单编号，标识该笔交易的唯一编号，每次请求的编号必须不一样，支持数字、英文字母组合使用
            registerMer.setMer_date(new SimpleDateFormat("yyyyMMdd").format(new Date()));   //交易的当前日期，格式YYYYMMDD
            registerMer.setSub_mer_id(String.valueOf(new Date().getTime()));    //产业链平台给企业商户分配的内部唯一编号
            registerMer.setSub_mer_type(payUmApplyForm.getSubMerType().toString());//商户类型，3（企业商户）、2（个体工商户）
            registerMer.setSub_mer_name(payUmApplyForm.getBankAccountName());   //营业执照上的商户名称，使用UTF-8编码,此字段上送的值需要与后续绑卡绑定企业对公户的bank_account_name相同
            registerMer.setSub_mer_alias(userInfo.getShopName()); //商户名称的业务别名，比如店铺名称
            registerMer.setCert_type(payUmApplyForm.getCertType().toString());  //证件类型，1：营业执照 2：统一社会信用代码
            registerMer.setCert_id(payUmApplyForm.getCertId());//证照号cert_type为1: 营业执照号码，长度为15，cert_type为2:信用代码证，长度为18位
            registerMer.setLegal_name(CipherUtil.encrypt(payUmApplyForm.getLegalName()));     //法人姓名
            registerMer.setIdentity_id(CipherUtil.encrypt(payUmApplyForm.getIdentityId()));   //法人证件号，仅支持18位身份证号
            registerMer.setContacts_name(CipherUtil.encrypt(payUmApplyForm.getContactsName())); //业务联系人姓名
            registerMer.setMobile_id(payUmApplyForm.getContactsMobileId());    //业务联系人的手机号
//            registerMer.setEmail("953799106@qq.com");
//            registerMer.setAddress("石家庄建设大街丰华路");

            logger.info("商户注册接入请求参数：" + registerMer);
            registerMer = registerMer.doRequest();
            logger.info("商户注册接入响应结果：" + registerMer);
            //注册不成功
            if(!registerMer.getRet_code().equals("0000")){
                return baseController.sendAjaxError(registerMer.getRet_msg());
            }

            //商户绑卡
            BindcardEnterprise bindcardEnterprise = new BindcardEnterprise();
            bindcardEnterprise.setMer_id("90000002");   //平台商户与联动签约后，链金平台分配给商户分配的唯一身份编号
            bindcardEnterprise.setOrder_id(String.valueOf(new Date().getTime()));   //订单编号，标识该笔交易的唯一编号，每次请求的编号必须不一样，支持数字、英文字母组合使用
            bindcardEnterprise.setMer_date(new SimpleDateFormat("yyyyMMdd").format(new Date()));     //交易的当前日期，格式YYYYMMDD
            bindcardEnterprise.setUser_id(registerMer.getUser_id());
//            bindcardEnterprise.setBank_account(CipherUtil.encrypt("1833012830001432")); //银行账户编号
            bindcardEnterprise.setBank_account(CipherUtil.encrypt(payUmApplyForm.getBankAccount())); //银行账户编号
            bindcardEnterprise.setBank_account_name(CipherUtil.encrypt(payUmApplyForm.getBankAccountName()));  //企业账户名称，要与商户注册时sub_mer_name一致
            bindcardEnterprise.setGate_id(payUmApplyForm.getGateId());   //银行编码，如中国工商银行:ICBC，当绑卡银行列表中不支持对应gate_id时，传入其他银行：QTYH
            bindcardEnterprise.setBank_branch_name(payUmApplyForm.getBankBranchName());     //按照开户许可证上的开户行支行全称，如：中国工商银行股份有限公司金融街支行
            bindcardEnterprise.setMobile_id(payUmApplyForm.getBankMobileId());    //提现到账通知手机号码

            logger.info("商户绑卡接入请求参数：" + bindcardEnterprise);
            bindcardEnterprise = bindcardEnterprise.doRequest();
            logger.info("商户绑卡接入响应结果：" + bindcardEnterprise);
            //注册不成功
            if(!bindcardEnterprise.getRet_code().equals("0000")){
                return baseController.sendAjaxError(bindcardEnterprise.getRet_msg());
            }

            payUmApplyForm.setSubUserId(bindcardEnterprise.getUser_id());
        } catch (Exception e) {
            e.printStackTrace();
        }

        PayUmApply payUmApply = new PayUmApply();
        BeanUtils.copyProperties(payUmApplyForm, payUmApply);
        payUmApply.setCheckState(1);  //审核状态
        payUmApply.setCreateUser(userInfo.getUserName());  //创建人
        payUmApply.setCreateDate(new Date());     //创建时间
        payUmApply.setModifyUser(userInfo.getUserName());   //修改人
        payUmApply.setModifyDate(new Date());           //修改时间，datax同步数据用
        payUmApply.setSubMerName(payUmApplyForm.getBankAccountName());  //营业执照上的商户名称，此字段上送的值需要与后续绑卡绑定企业对公户的bank_account_name相同
        payUmApply.setUserCode(userInfo.getUserCode());
        payUmApply.setUserName(userInfo.getUserName());
        payUmApply.setSubMerAlias(userInfo.getShopName());
        logger.info("商户信息入库参数：{}", JSON.toJSONString(payUmApply));

        payUmApplyWriteMapper.insert(payUmApply);

        return baseController.sendAjaxOK();
    }

    /*
        注册个人联动链金
     */
    @Override
    public BaseResponse addPayUmApplyPerson(PayUmApplyForm payUmApplyForm, ErpUserInfo userInfo) {
        BaseController baseController = new BaseController();

        try {
            //个人注册
            RegisterPersonal registerPersonal = new RegisterPersonal();
            registerPersonal.setMer_id("90000002");
//        registerPersonal.setNotify_url("http://www.baidu.com");
            registerPersonal.setOrder_id(String.valueOf(new Date().getTime()));//商户自己维护留存的订单号
            registerPersonal.setMer_date(new SimpleDateFormat("yyyyMMdd").format(new Date()));
            registerPersonal.setMer_cust_id(String.valueOf(new Date().getTime()));//商户自己维护留存的客户号
            registerPersonal.setUser_type("1");     //商户类型，固定值：1（个人商户）
            registerPersonal.setMobile_id(payUmApplyForm.getBankMobileId());   //商户手机号
            registerPersonal.setCust_name(CipherUtil.encrypt(userInfo.getUserName()));   //真实姓名
            registerPersonal.setIdentity_type("1"); //证件类型，固定值：1（居民身份证）
            registerPersonal.setIdentity_code(CipherUtil.encrypt(payUmApplyForm.getIdentityId())); //证件号，用联动的公钥进行RSA加密后，BASE64(GBK编码)加密该字段

            logger.info("商户接入请求参数：" + registerPersonal);
            registerPersonal = registerPersonal.doRequest();
            logger.info("商户接入响应结果：" + registerPersonal);
            //注册不成功
            if(!registerPersonal.getRet_code().equals("0000")){
                return baseController.sendAjaxError(registerPersonal.getRet_msg());
            }

            //个人绑卡
            BindcardOrder bindcardOrder = new BindcardOrder();
            bindcardOrder.setMer_id("90000002");
            bindcardOrder.setOrder_id(String.valueOf(new Date().getTime()));//商户自己维护的订单号
            bindcardOrder.setMer_date(new SimpleDateFormat("yyyyMMdd").format(new Date()));
            bindcardOrder.setUser_id(registerPersonal.getUser_id());//入网获得
            bindcardOrder.setUser_type("1");    //商户类型，固定值：1（个人商户）
            bindcardOrder.setCard_id(CipherUtil.encrypt(payUmApplyForm.getBankAccount()));    //卡号
            bindcardOrder.setBank_account_name(CipherUtil.encrypt(payUmApplyForm.getBankAccountName()));  //持卡人名
            bindcardOrder.setBank_mobile_id(payUmApplyForm.getBankMobileId());//银行预留手机号
//		bindcardOrder.setNotify_url("http://商户接收后台通知的地址");

            logger.info("商户接入请求参数：" + bindcardOrder);
            bindcardOrder = bindcardOrder.doRequest();
            logger.info("商户接入响应结果：" + bindcardOrder);
            //注册不成功
            if(!bindcardOrder.getRet_code().equals("0000")){
                return baseController.sendAjaxError(bindcardOrder.getRet_msg());
            }

            payUmApplyForm.setUmUserId(registerPersonal.getUser_id());
            payUmApplyForm.setTradeNo(bindcardOrder.getTrade_no());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("联动链金企业注册异常，{}",e);
            return baseController.sendAjaxError("操作异常");
        }

        Map<String,Object> map = new HashMap<>();
        map.put("payUmApply", payUmApplyForm);
        return baseController.sendAjaxOK(map);
    }

    /*
    绑定银行卡-确认
     */
    @Override
    @Transactional(value = "writeTransactionManager")
    public BaseResponse bindcardConfirm(PayUmApplyForm payUmApplyForm, ErpUserInfo userInfo) {
        BaseController baseController = new BaseController();

        try {

            BindcardConfirm bindcardConfirm = new BindcardConfirm();
            bindcardConfirm.setMer_id("90000002");
            bindcardConfirm.setTrade_no(payUmApplyForm.getTradeNo());    //联动在绑定法人结算卡申请接口中返回的trade_no参数
            bindcardConfirm.setUser_id(payUmApplyForm.getUmUserId()); //子商户在联动链金平台注册成功后，联动返回的子商户唯一编号
            bindcardConfirm.setVerify_code(payUmApplyForm.getVerifyCode());     //子商户绑卡申请时，联动链金平台下发到子商户银行预留手机的验证码，(1)验证码有效期:9000秒，(2)最多下发次数:3次，(3)最多允许错误次数:5次

            logger.info("商户接入请求参数：" + bindcardConfirm);
            bindcardConfirm = bindcardConfirm.doRequest();
            logger.info("商户接入响应结果：" + bindcardConfirm);

            //注册不成功
            if(!bindcardConfirm.getRet_code().equals("0000")){
                return baseController.sendAjaxError(bindcardConfirm.getRet_msg());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        PayUmApply payUmApply = new PayUmApply();
        BeanUtils.copyProperties(payUmApplyForm, payUmApply);
        payUmApply.setCheckState(1);  //审核状态
        payUmApply.setCreateUser(userInfo.getUserName());  //创建人
        payUmApply.setCreateDate(new Date());     //创建时间
        payUmApply.setModifyUser(userInfo.getUserName());   //修改人
        payUmApply.setModifyDate(new Date());           //修改时间，datax同步数据用
        payUmApply.setUserName(userInfo.getUserName());
        payUmApply.setUserCode(userInfo.getUserCode());
        payUmApply.setSubMerType(1);   //3（企业商户）、2（个体工商户）、1（个人）
        payUmApply.setSubMerAlias(userInfo.getShopName());
        payUmApply.setSubUserId(payUmApplyForm.getUmUserId());
        logger.info("商户信息入库参数：{}", JSON.toJSONString(payUmApply));

        payUmApplyWriteMapper.insert(payUmApply);

        return baseController.sendAjaxOK();
    }

    /*
    查询商户的联动链金注册信息
     */
    @Override
    @Transactional(value="readTransactionManager")
    public PayUmApplyForm getpayUmApplyByUserCode(String userCode) {
        PayUmApplyForm payUmApplyForm = payUmApplyReadMapper.getpayUmApplyByUserCode(userCode);
        return payUmApplyForm;
    }

    /*
    查询联动链金注册信息
     */
    @Override
    @Transactional(value="readTransactionManager")
    public BaseResponse getPayUmApplyList(PayUmApplyDTO payUmApplyDTO) {
        BaseController baseController = new BaseController();

        PayUmApplyForm payUmApplyForm =new PayUmApplyForm();
        BeanUtils.copyProperties(payUmApplyDTO, payUmApplyForm);

        //封装分页
        PageHelper.startPage(payUmApplyDTO.getPageNum(), payUmApplyDTO.getPageSize());
        List<PayUmApplyForm> payUmApplyFormList = payUmApplyReadMapper.getPayUmApplyList(payUmApplyForm);

        XePageInfo<PayUmApplyForm> pageInfo =  new XePageInfo<>(payUmApplyFormList);
        Map<String,Object> map = new HashMap<>();
        map.put("pageInfo",pageInfo);
        map.put("whiteList", payUmApplyFormList);
        map.put("picServer", env.getProperty("manager.imgUrl"));

        return baseController.sendAjaxOK(map);
    }

    /*
    查询所有联动链金注册信息
     */
    @Override
    @Transactional(value="readTransactionManager")
    public List<PayUmApplyDTO>  getPayUmApplyListByModel(PayUmApplyDTO payUmApplyDTO) {
        PayUmApplyForm payUmApplyForm = new PayUmApplyForm();
        BeanUtils.copyProperties(payUmApplyDTO, payUmApplyForm);
        List<PayUmApplyForm> payUmApplyFormList = payUmApplyReadMapper.getPayUmApplyList(payUmApplyForm);

        List<PayUmApplyDTO> payUmApplyDTOList = new ArrayList();
        for (PayUmApplyForm payUmApplyForm2: payUmApplyFormList){
            PayUmApplyDTO payUmApplyDTO2 = new PayUmApplyDTO();
            BeanUtils.copyProperties(payUmApplyForm2, payUmApplyDTO2);
            payUmApplyDTOList.add(payUmApplyDTO2);
        }
        return payUmApplyDTOList;
    }

    /*
    根据id查询联动链金注册信息-
     */
    @Override
    @Transactional(value="readTransactionManager")
    public PayUmApplyForm getPayUmApplyById(Integer id) {
        PayUmApply payUmApply = payUmApplyReadMapper.selectByPrimaryKey(id);

        PayUmApplyForm payUmApplyForm = new PayUmApplyForm();
        BeanUtils.copyProperties(payUmApply, payUmApplyForm);

        return payUmApplyForm;
    }

    /*
    联动链金注册信息
     */
    @Override
    @Transactional(value = "writeTransactionManager")
    public BaseResponse auditPayUmApply(PayUmApplyDTO payUmApplyDTO, String loginName) {
        BaseController baseController = new BaseController();

        for(Integer id: payUmApplyDTO.getIds()){
            PayUmApply payUmApply = new PayUmApply();
            payUmApply.setId(id);
            payUmApply.setCheckMan(loginName);
            payUmApply.setCheckState(WhiteListCheckStateEnum.success.getValue());
            payUmApply.setCheckDate(new Date());
            payUmApply.setRemark(payUmApplyDTO.getRemark());
            payUmApply.setModifyUser(loginName);   //修改人
            payUmApply.setModifyDate(new Date());           //修改时间，datax同步数据用
            payUmApplyWriteMapper.updateByPrimaryKeySelective(payUmApply);
        }

        return baseController.sendAjaxOK();
    }

    /*
    禁用联动链金的注册
     */
    @Override
    @Transactional(value = "writeTransactionManager")
    public BaseResponse disablePayUmApply(PayUmApplyDTO payUmApplyDTO, String loginName) {
        BaseController baseController = new BaseController();

        for(Integer id: payUmApplyDTO.getIds()){
            PayUmApply payUmApply = new PayUmApply();
            payUmApply.setId(id);
            payUmApply.setCheckMan(loginName);
            payUmApply.setCheckState(WhiteListCheckStateEnum.disable.getValue());
            payUmApply.setCheckDate(new Date());
            payUmApply.setRemark(payUmApplyDTO.getRemark());
            payUmApply.setModifyUser(loginName);   //修改人
            payUmApply.setModifyDate(new Date());           //修改时间，datax同步数据用
            payUmApplyWriteMapper.updateByPrimaryKeySelective(payUmApply);
        }

        return baseController.sendAjaxOK();
    }

}
